package com.sdwl.brcl.validation.validation;

import java.util.Collection;

/**
 * @author xied
 * @date 2021年06月11日 14:14
 */
public class CollectionValidator implements Validator {
    public static final int MUST_EMPTY = 0;
    public static final int MIN_SIZE = 1;
    public static final int MAX_SIZE = 2;
    public static final int EQ_SIZE = 3;
    private int type;

    public CollectionValidator(int type) {
        this.type = type;
    }

    @Override
    public boolean validate(Object value) {
        if (this.type == 0) {
            return value == null || ((Collection)value).isEmpty();
        } else {
            Object[] values;
            Collection collection;
            if (this.type == 1) {
                values = (Object[])((Object[])value);
                collection = (Collection)values[0];
                return collection != null && collection.size() >= (Integer)values[1];
            } else if (this.type == 2) {
                values = (Object[])((Object[])value);
                collection = (Collection)values[0];
                return collection == null || collection.size() <= (Integer)values[1];
            } else if (this.type != 3) {
                throw new UnsupportedOperationException("不支持的集合操作");
            } else {
                values = (Object[])((Object[])value);
                collection = (Collection)values[0];
                return collection != null && collection.size() == (Integer)values[1];
            }
        }
    }

    @Override
    public String validateCode() {
        if (this.type == 0) {
            return "must.empty";
        } else if (this.type == 1) {
            return "min.size";
        } else if (this.type == 2) {
            return "max.size";
        } else {
            return this.type == 3 ? "eq.size" : "";
        }
    }

    @Override
    public String validateMsg(Object value, String validateName) {
        if (this.type == 0) {
            return validateName + "必须为空";
        } else {
            Object[] values;
            if (this.type == 1) {
                values = (Object[])((Object[])value);
                return validateName + "允许最小大小为" + values[1];
            } else if (this.type == 2) {
                values = (Object[])((Object[])value);
                return validateName + "允许最大大小为" + values[1];
            } else if (this.type == 3) {
                values = (Object[])((Object[])value);
                return validateName + "大小必须为" + values[1];
            } else {
                return "";
            }
        }
    }
}
